#!/bin/bash

# 1. 安装配置 earlyoom
dnf install -y earlyoom
cat > /etc/default/earlyoom << EOF
EARLYOOM_ARGS="-m 5 -s 20 -n 4 --avoid '^(systemd|sshd|mysqld|postgres|redis|java|nginx|crond)'"
EOF
systemctl enable --now earlyoom

# 2. 安全的内存过度分配配置
cat >> /etc/sysctl.conf << EOF
# 安全内存分配策略
vm.overcommit_memory = 2
vm.overcommit_ratio = 90
# 减少交换倾向（优先保持内存）
vm.swappiness = 10
EOF
sysctl -p

# 3. 关键进程 OOM 保护（系统启动时执行）
cat > /etc/systemd/system/oom-protect.service << EOF
[Unit]
Description=Critical Process OOM Protection
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/bash -c '/bin/echo -1000 > /proc/\$(pgrep -o systemd)/oom_score_adj'
ExecStart=/bin/bash -c '/bin/echo -1000 > /proc/\$(pgrep -o sshd)/oom_score_adj'
ExecStart=/bin/bash -c 'for p in \$(pgrep mysqld); do echo -1000 > /proc/\$p/oom_score_adj; done'
ExecStart=/bin/bash -c 'for p in \$(pgrep redis); do echo -1000 > /proc/\$p/oom_score_adj; done'
ExecStart=/bin/bash -c 'for p in \$(pgrep java); do echo -500 > /proc/\$p/oom_score_adj; done'

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable oom-protect.service
systemctl start oom-protect.service